<template>
  <div class="clue-list-container">
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <span>线索管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleCreate">新增线索</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryForm" inline class="query-form">
        <el-form-item label="线索姓名">
          <el-input v-model="queryForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="线索来源">
          <el-select v-model="queryForm.source" placeholder="请选择来源" clearable>
            <el-option label="官网" value="WEBSITE" />
            <el-option label="电话" value="PHONE" />
            <el-option label="邮件" value="EMAIL" />
            <el-option label="展会" value="EXHIBITION" />
            <el-option label="推荐" value="REFERRAL" />
            <el-option label="广告" value="ADVERTISEMENT" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="新建" value="NEW" />
            <el-option label="已分配" value="ASSIGNED" />
            <el-option label="已领取" value="CLAIMED" />
            <el-option label="已转化" value="CONVERTED" />
            <el-option label="已回收" value="RECYCLED" />
            <el-option label="自动回收" value="AUTO_RECYCLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="queryForm.priority" placeholder="请选择优先级" clearable>
            <el-option label="高" value="HIGH" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="低" value="LOW" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 线索列表 -->
      <el-table
        :data="clueList"
        v-loading="loading"
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column
          prop="name"
          label="姓名"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          prop="company"
          label="公司"
          min-width="150"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column prop="position" label="职位" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.position || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.phone || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="140" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.email || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getSourceType(row.source)" size="small" effect="light">
              {{ getSourceName(row.source) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small" effect="light">
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small" effect="light">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ownerName" label="负责人" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.ownerName || '未分配' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" fixed="right" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" link @click="handleView(row)">查看</el-button>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button
                v-if="row.status !== 'CONVERTED'"
                type="warning"
                link
                @click="handleConvert(row)"
              >
                转化
              </el-button>
              <el-button
                v-if="row.status === 'ASSIGNED' || row.status === 'RECEIVED'"
                type="info"
                link
                @click="handleFollowUp(row)"
              >
                跟进中
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 线索转化对话框 -->
    <el-dialog
      v-model="showConvertDialog"
      title="线索转化"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="convertForm" ref="convertFormRef" label-width="80px">
        <el-form-item label="转化类型" prop="convertType">
          <el-select v-model="convertForm.convertType" placeholder="请选择转化类型">
            <el-option
              v-for="(label, value) in ConvertTypeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <template v-if="convertForm.convertType === ConvertType.CUSTOMER">
          <el-form-item label="选择部门" prop="departmentId">
            <el-select
              v-model="convertForm.departmentId"
              placeholder="请选择部门"
              @change="handleDepartmentChange"
            >
              <el-option
                v-for="dept in departmentList"
                :key="dept.id"
                :label="dept.fullName"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="销售人员" prop="ownerId">
            <el-select
              v-model="convertForm.ownerId"
              placeholder="请选择销售人员"
              :disabled="!convertForm.departmentId"
            >
              <el-option
                v-for="user in departmentUsers"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else-if="convertForm.convertType === ConvertType.OPPORTUNITY">
          <el-form-item label="选择客户" prop="customerId">
            <el-input
              v-model="convertForm.customerName"
              placeholder="请选择客户"
              readonly
              @click="openCustomerDialog"
            >
              <template #append>
                <el-button @click="openCustomerDialog">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </template>
        <el-form-item label="转化原因" prop="convertReason">
          <el-input
            v-model="convertForm.convertReason"
            type="textarea"
            :rows="3"
            placeholder="请输入转化原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConvertDialog = false">取消</el-button>
          <el-button type="primary" @click="submitConvert" :loading="submitting">转化</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 客户选择对话框 -->
    <el-dialog
      v-model="showCustomerDialog"
      title="选择客户"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table
        :data="customerList"
        v-loading="customerLoading"
        stripe
        highlight-current-row
        style="width: 100%"
        @row-click="handleSelectCustomer"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="客户名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="industry" label="所属行业" width="120" align="center" />
        <el-table-column prop="region" label="所在地区" width="120" align="center" />
        <el-table-column prop="contactName" label="联系人" width="120" align="center" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClues, deleteClue, convertClue, followupClue } from '@/api/clue'
import type { Clue } from '@/types/clue'
import type { Department } from '@/api/department'
import type { User } from '@/api/user'
import axios from 'axios'
import { getAllDepartments } from '@/api/department'
import { getDepartmentUsers } from '@/api/user'
import { searchCustomers as searchCustomersApi } from '@/api/customer'

// 定义转化类型枚举
const ConvertType = {
  CUSTOMER: 'CUSTOMER',
  OPPORTUNITY: 'OPPORTUNITY',
} as const

type ConvertType = (typeof ConvertType)[keyof typeof ConvertType]

const ConvertTypeMap = {
  [ConvertType.CUSTOMER]: '转化为客户',
  [ConvertType.OPPORTUNITY]: '转化为商机',
} as const

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const clueList = ref<Clue[]>([])

const queryForm = reactive({
  name: '',
  source: '',
  status: '',
  priority: '',
})

// 转化相关
const showConvertDialog = ref(false)
const convertFormRef = ref()
const convertForm = reactive({
  convertType: undefined as ConvertType | undefined,
  convertReason: '',
  departmentId: undefined as number | undefined,
  ownerId: undefined as number | undefined,
  customerId: undefined as number | undefined,
  customerName: undefined as string | undefined,
})
let currentConvertClueId: number | null = null
const departmentList = ref<Department[]>([])
const departmentUsers = ref<User[]>([])

// 添加客户选择相关
const showCustomerDialog = ref(false)
const customerList = ref<any[]>([])
const customerLoading = ref(false)
const customerTotal = ref(0)
const selectedCustomer = ref<any>(null)

const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      ...queryForm,
    }
    const res = await getClues(params)
    clueList.value = res.data.content
    total.value = res.data.totalElements
  } catch (error) {
    console.error('加载线索列表失败:', error)
    ElMessage.error('加载线索列表失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  currentPage.value = 1
  loadData()
}

const resetQuery = () => {
  Object.assign(queryForm, {
    name: '',
    source: '',
    status: '',
    priority: '',
  })
  handleQuery()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadData()
}

const handlePageChange = (val: number) => {
  currentPage.value = val
  loadData()
}

const handleCreate = () => {
  router.push('/clues/create')
}

const handleEdit = (row: Clue) => {
  router.push(`/clues/${row.id}/edit`)
}

const handleView = (row: Clue) => {
  router.push(`/clues/${row.id}`)
}

const handleDelete = async (row: Clue) => {
  try {
    await ElMessageBox.confirm('确认删除该线索吗？', '提示', {
      type: 'warning',
    })
    await deleteClue(row.id!)
    ElMessage.success('删除成功')
    await recordOperation('DELETE_CLUE', `删除线索：${row.name}`)
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除线索失败:', error)
      ElMessage.error('删除线索失败')
    }
  }
}

const handleFollowUp = async (row: Clue) => {
  try {
    await followupClue(row.id!)
    ElMessage.success('操作成功')
    await recordOperation('FOLLOWUP_CLUE', `跟进线索：${row.name}`)
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('跟进线索失败:', error)
      ElMessage.error('跟进线索失败')
    }
  }
}

const handleConvert = async (row: Clue) => {
  currentConvertClueId = row.id!
  convertForm.convertType = undefined
  convertForm.convertReason = ''
  convertForm.departmentId = undefined
  convertForm.ownerId = undefined
  convertForm.customerId = undefined
  convertForm.customerName = undefined
  showConvertDialog.value = true
  await loadDepartments()
}

const loadDepartments = async () => {
  try {
    const res = await getAllDepartments()
    departmentList.value = res.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

const handleDepartmentChange = async (departmentId: number) => {
  convertForm.ownerId = undefined
  if (departmentId) {
    try {
      const res = await getDepartmentUsers(departmentId)
      departmentUsers.value = res.data
    } catch (error) {
      console.error('获取部门用户失败:', error)
      ElMessage.error('获取部门用户失败')
    }
  } else {
    departmentUsers.value = []
  }
}

// 加载客户列表
const loadCustomers = async () => {
  customerLoading.value = true
  try {
    const res = await searchCustomersApi('')
    customerList.value = res.data.content
    customerTotal.value = res.data.totalElements
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败')
  } finally {
    customerLoading.value = false
  }
}

// 打开客户选择对话框
const openCustomerDialog = async () => {
  showCustomerDialog.value = true
  await loadCustomers()
}

// 选择客户
const handleSelectCustomer = (customer: any) => {
  selectedCustomer.value = customer
  convertForm.customerId = customer.id
  convertForm.customerName = customer.name
  showCustomerDialog.value = false
}

const submitConvert = async () => {
  if (!convertForm.convertType || !convertForm.convertReason) {
    ElMessage.warning('请填写完整的转化信息')
    return
  }

  if (convertForm.convertType === ConvertType.CUSTOMER) {
    if (!convertForm.departmentId || !convertForm.ownerId) {
      ElMessage.warning('请选择部门和销售人员')
      return
    }
  } else if (convertForm.convertType === ConvertType.OPPORTUNITY) {
    if (!convertForm.customerId) {
      ElMessage.warning('请选择客户')
      return
    }
  }

  submitting.value = true
  try {
    await convertClue(currentConvertClueId!, convertForm)
    ElMessage.success('转化成功')
    await recordOperation('CONVERT_CLUE', `转化线索为${ConvertTypeMap[convertForm.convertType!]}`)
    showConvertDialog.value = false
    loadData()
  } catch (error) {
    console.error('转化线索失败:', error)
    ElMessage.error('转化线索失败')
  } finally {
    submitting.value = false
  }
}

// 获取来源类型样式
const getSourceType = (source: string) => {
  const types: Record<string, string> = {
    WEBSITE: 'primary',
    PHONE: 'success',
    EMAIL: 'info',
    EXHIBITION: 'warning',
    REFERRAL: 'danger',
    ADVERTISEMENT: 'primary',
    OTHER: 'info',
  }
  return types[source] || 'info'
}

// 获取来源名称
const getSourceName = (source: string) => {
  const names: Record<string, string> = {
    WEBSITE: '官网',
    PHONE: '电话',
    EMAIL: '邮件',
    EXHIBITION: '展会',
    REFERRAL: '推荐',
    ADVERTISEMENT: '广告',
    OTHER: '其他',
  }
  return names[source] || source
}

// 获取优先级类型样式
const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    HIGH: 'danger',
    MEDIUM: 'warning',
    LOW: 'success',
  }
  return types[priority] || 'info'
}

// 获取优先级名称
const getPriorityName = (priority: string) => {
  const names: Record<string, string> = {
    HIGH: '高',
    MEDIUM: '中',
    LOW: '低',
  }
  return names[priority] || priority
}

// 获取状态类型样式
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    NEW: 'info',
    ASSIGNED: 'warning',
    CLAIMED: 'primary',
    CONVERTED: 'success',
    RECYCLED: 'danger',
    AUTO_RECYCLED: 'danger',
  }
  return types[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const names: Record<string, string> = {
    NEW: '新建',
    ASSIGNED: '已分配',
    CLAIMED: '已领取',
    CONVERTED: '已转化',
    RECYCLED: '已回收',
    AUTO_RECYCLED: '自动回收',
  }
  return names[status] || status
}

// 记录操作日志
const recordOperation = async (action: string, description: string) => {
  try {
    await axios.post('/api/logs', {
      action,
      description,
    })
  } catch (error) {
    console.error('记录操作日志失败:', error)
  }
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问线索管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

onMounted(() => {
  loadData()
  recordPageAccess()
})
</script>
<style scoped>
.clue-list-container {
  padding: 20px;
}

.role-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table {
  margin: 0 20px;
}

.el-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
  padding: 8px 0;
}

.el-table :deep(td) {
  padding: 12px 0;
  height: 50px;
}

.el-table :deep(.cell) {
  line-height: 1.5;
  white-space: nowrap;
  padding: 0 12px;
}

.table-cell-text {
  color: #606266;
  font-size: 14px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
